package com.googlecode.imule.discovery;

import com.apple.dnssd.BrowseListener;
import com.apple.dnssd.DNSSDService;

/**
 * This class simply reacts to events from the service browser, maintaining a
 * list of contacts from these events. The callbacks here are a consequence of
 * the DNSSD.browse(...) method call in the Discovery constructor. 
 * 
 * @author Graham Williamson, Neil Cowzer
 */
public class BrowserAdaptor implements BrowseListener {

	/** List of contacts we know about */
	private ContactList contactList;
	
	/**
	 * A browser adaptor listens for browse updates and maintains a contact
	 * list based on these updates.
	 * 
	 * @param contactList the contact list to maintain.
	 */
	public BrowserAdaptor(ContactList contactList) {
		this.contactList = contactList;
	}
	
	/**
	 * This callback is invoked when a node joins the network.
	 * 
	 * @see com.apple.dnssd.BrowseListener#serviceFound(com.apple.dnssd.DNSSDService, int, int, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void serviceFound(DNSSDService browser, int flags, int ifIndex, String serviceName, String regType, String domain) {
		System.out.println("**Found Service** " + serviceName);
		contactList.addContact(serviceName, domain, regType, ifIndex);
	}

	/**
	 * This callback is invoked when a node leaves the network.	
	 * 
	 * @see com.apple.dnssd.BrowseListener#serviceLost(com.apple.dnssd.DNSSDService, int, int, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void serviceLost(DNSSDService browser, int flags, int ifIndex, String serviceName, String regType, String domain) {
		System.out.println("**Lost Service** " + serviceName);
		contactList.removeContact(serviceName);
	}

	/**
	 * This callback is invoked when something goes wrong during a browse...
	 * 
	 * @see com.apple.dnssd.BaseListener#operationFailed(com.apple.dnssd.DNSSDService, int)
	 */
	public void operationFailed(DNSSDService service, int errorCode) {
		System.out.println("Browsing error with service " + service.toString() + ". Error code: " + errorCode);
	}

}
